package com.cofi.vueelementadminserver.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.util.Enumeration;

/**
 * @author xyh
 * @date 2025-01-08
 * @description 请求详情过滤器
 */
public class RequestLogFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String contentType = request.getContentType();
        System.out.println("===============================TestFilter doFilter start==================================");
        System.out.println("Request-URL:" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath() );
        System.out.println("User-Agent:" + request.getHeader("User-Agent") );
        System.out.println("Request-Method:" + request.getMethod());
        System.out.println("Content-Type: " + contentType);
        this.printRequestParamDetail(request);

//        if(request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())){
//            if(contentType.equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_VALUE)){
//                //form请求
//            }else if(contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || contentType.equalsIgnoreCase(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE)){
//                //ajax请求
//            }
//        }else if(request.getMethod().equalsIgnoreCase(HttpMethod.GET.name())){
//            this.printParamDetail(request);
//        }
        System.out.println("===============================TestFilter doFilter end==================================");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    public void printRequestParamDetail(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        System.out.println("param:{");
        if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.toString()))
            while (parameterNames.hasMoreElements()) {
                String key = parameterNames.nextElement();
                String value = request.getParameter(key);
                System.out.println("\t" + key + "=" + value);
            }
        System.out.println("}");
    }
}
